package com.tuhao.www.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

/**
 *
 * 拦截防止xss注入
 *
 */
public class XssFilter implements Filter {

    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    // 需要过滤的页面地址字符串，多个用半角逗号分隔
    private String excludeUrl;

    // 需要过滤的页面地址数组，经过excludeUrl对,进行split得到
    private String[] excludeUrlArray;

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setContentType(CONTENT_TYPE);

        String currentUrl = httpRequest.getServletPath();
        boolean flag = false;
        if (excludeUrlArray != null && excludeUrlArray.length > 0) {
            for (String regex : excludeUrlArray) {
                if (this.matches(regex.trim(), currentUrl.trim())) {
                    flag = true;
                    break;
                }
            }
        }
        if(flag){

            filterChain.doFilter(httpRequest, response);
        } else {
            XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
            filterChain.doFilter(xssRequest, response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.excludeUrl = filterConfig.getInitParameter("excludeUrl");
        if (excludeUrl != null) {
            excludeUrlArray = excludeUrl.split(",");
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 通过正则表达式匹配字符串
     *
     * @param regex
     *            String
     * @param input
     *            CharSequence
     * @return boolean
     */
    private boolean matches(String regex, CharSequence input) {
        if (regex == null || input == null) {
            return true;
        } else if (regex.equals(input)) {
            return true;
        } else if (regex.indexOf("*") > -1) {
            PathMatcher pathMatcher = new AntPathMatcher();
            return pathMatcher.match(regex, input.toString());
        } else {
            return false;
        }
    }

}